import mongoose from "mongoose";
import Logger from "../common/logger";
import { IMyTrade} from "../types";

class MyTradeModel {
    public readonly  model: mongoose.Model<IMyTrade>;
    public readonly logger: Logger;
    constructor(db:mongoose.Connection, col_name:string, schema:mongoose.Schema, logger:Logger) {
        this.model = db.model<IMyTrade>(col_name, schema);
        this.logger = logger;

    }
    async insertTrade(docData:IMyTrade) {
        try{
            let id = docData.id;
            let oldDoc = await this.model.findOne({id:id});
            if(oldDoc === null) {
                let doc = new this.model(docData);
                let newDoc = await doc.save();
                if(newDoc) {
                    this.logger.debug("insertTrade, newDoc: ", newDoc);
                }
            }
        }catch (e) {
            this.logger.error("insertTrade e: ",e);
        }
    }
    async findTradeByFilter(filter:Object, projection:Object) {
        try{
            if(projection) {
                let docs = await this.model.find(filter, projection);
                return docs;
            }else{
                let docs = await this.model.find(filter);
                return docs;
            }

        }
        catch(e) {
            this.logger.error("insertKline e: ",e);
        }
    }
    async  updateTrade(filter:Object, updateDoc:Object){
        try{
            let res = await this.model.updateOne(filter, updateDoc);
            if(res){
                return true;
            }else{
                return false;
            }
        }catch (e) {
            this.logger.error("updateKline e: ",e);
            return false;
        }
    }
}
export default MyTradeModel;